<template>
  <div class="login-container">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名" />
      </el-form-item>
      
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="form.password"
          type="password"
          placeholder="请输入密码"
          show-password
        />
      </el-form-item>
      
      <el-form-item v-if="!isLogin" label="确认密码" prop="confirmPassword">
        <el-input
          v-model="form.confirmPassword"
          type="password"
          placeholder="请再次输入密码"
          show-password
        />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">
          {{ isLogin ? '登录' : '注册' }}
        </el-button>
        <el-button @click="toggleMode">
          切换到{{ isLogin ? '注册' : '登录' }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { login } from '@/api/auth.js' // 引入登录接口

const emit = defineEmits(['login-success'])
const userStore = useUserStore()
const formRef = ref(null)
const isLogin = ref(true)

const form = reactive({
  username: '',
  password: '',
  confirmPassword: ''
})

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (form.confirmPassword !== '') {
      formRef.value?.validateField('confirmPassword')
    }
    callback();
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== form.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, validator: validatePass, trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePass2, trigger: 'blur' }
  ]
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isLogin.value) {
          // 调用后端登录接口
          await userStore.login({
            username: form.username,
            password: form.password
          })
          if (response.data && response.data.token) {
            // 登录成功
            userStore.setToken(response.data.token) // 假设后端返回 token
            ElMessage.success('登录成功')
            emit('login-success')
          } else {
            // 登录失败
            ElMessage.error(response.data.message || '登录失败，请检查用户名或密码')
          }
        } else {
          // 注册逻辑
          const registerResponse = await userStore.register({
            username: form.username,
            password: form.password
          });
          if (registerResponse.data && registerResponse.data.code === 200) {
            ElMessage.success('注册成功');
            isLogin.value = true;
            form.confirmPassword = '';
          } else {
            ElMessage.error(registerResponse.data.message || '注册失败，请重试');
          }
        }
      } catch (error) {
        console.error(error);
        ElMessage.error('请求失败，请重试');
      }
    }
  });
}

// const handleLogin = async () => {
//   try {
//     // 模拟登录逻辑
//     userStore.login('mock-token')
//     ElMessage.success('登录成功')
//     // 通知父组件登录成功
//     emit('login-success')
//   } catch (error) {
//     ElMessage.error('登录失败，请重试')
//   }
// }

const toggleMode = () => {
  isLogin.value = !isLogin.value
  formRef.value?.resetFields()
}
</script>

<style scoped>
.login-container {
  padding: 20px;
}
</style> 